package com.example.demo.controller;

import com.example.demo.entito.Product;
import com.example.demo.mapper.ProductMapper;
import com.example.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
@Api(tags = {"esApi学习接口"})
@RequestMapping("esApi")
public class ProductController {


//    {
//        "category": "手机",
//            "id": 1,
//            "images": "images",
//            "price": 123.0,
//            "title": "小米手机"
//    }

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @ApiOperation("es新增数据")
    @PostMapping("/save")
    public Result save(@RequestBody Product product){
        Product save = productMapper.save(product);
        return Result.ok(save);
    }

    @ApiOperation("es更新数据")
    @PostMapping("/update/{id}")
    public Result update(@PathVariable("id") Long id){
        Optional<Product> product = productMapper.findById(id);
        Product product1 = product.get();
        product1.setImages("12345689");
        Product save = productMapper.save(product1);
        return Result.ok(save);
    }


    @ApiOperation("es删除数据")
    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Long id){
        productMapper.deleteById(id);
        return Result.ok();
    }

    @ApiOperation("es批量新增数据")
    @PostMapping("/saveAll")
    public Result saveAll(){
        List<Product> productList = new ArrayList<>();
        for (int i = 3; i <100 ; i++) {
            Product product = new Product();
            product.setId(Long.valueOf(i));
            product.setTitle("["+i+"]小米手机");
            product.setCategory("手机");
            product.setPrice(1999.0+i);
            product.setImages("http://www.atguigu/xm.jpg");
            productList.add(product);
        }
        productMapper.saveAll(productList);
        return Result.ok(productList);
    }

    @ApiOperation("es分页查询")
    @PostMapping("/findByPageable/{currentPahge}/{pageSize}")
    public Result findByPageable(@PathVariable("currentPahge") int currentPahge,
                                 @PathVariable("pageSize") int pageSize){
        // 分页构造器
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        PageRequest pageRequest = PageRequest.of(currentPahge, pageSize, sort);
        Page<Product> productPage = productMapper.findAll(pageRequest);
        return Result.ok(productPage);
    }

    @ApiOperation("es文档搜索")
    @PostMapping("/termQuery/{termQuery}")
    public Result termQuery(@PathVariable("termQuery") String termQuery){
        //根据一个值查询多个字段  并高亮显示  这里的查询是取并集，即多个字段只需要有一个字段满足即可
        //需要查询的字段
        BoolQueryBuilder boolQueryBuilder= QueryBuilders.boolQuery()
                .filter(QueryBuilders.matchQuery("title",termQuery));

        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder).build();

        SearchHits<Product> search = elasticsearchRestTemplate.search(searchQuery, Product.class);

        return Result.ok(search);
    }


    @ApiOperation("es文档搜索and分页")
    @PostMapping("/termQuery/{termQuery}/{currentPahge}/{pageSize}")
    public Result findByPageableTermQuery(@PathVariable("termQuery") String termQuery,
                                          @PathVariable("currentPahge") Integer currentPahge,
                                          @PathVariable("pageSize") Integer pageSize){
        //根据一个值查询多个字段  并高亮显示  这里的查询是取并集，即多个字段只需要有一个字段满足即可
        //需要查询的字段
        BoolQueryBuilder boolQueryBuilder= QueryBuilders.boolQuery()
                .filter(QueryBuilders.matchQuery("title",termQuery))
                ;

        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        PageRequest pageRequest = PageRequest.of(currentPahge, pageSize, sort);

        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder).build()
                .setPageable(pageRequest);

        SearchHits<Product> search = elasticsearchRestTemplate.search(searchQuery, Product.class);
        return Result.ok(search);
    }






}
